<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>闪零门店助手</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      height: 100vh;
      display: flex;
      flex-direction: column;
      background: #f5f5f5;
    }
    .tabs-container {
      background: #e8e8e8;
      border-bottom: 2px solid #e0e0e0;
      display: flex;
      align-items: flex-end;
      overflow-x: auto;
      overflow-y: hidden;
      min-height: 35px;
      padding: 0px 8px 0 8px;
      position: relative;
      z-index: 100;
    }
    .tabs-wrapper {
      display: flex;
      align-items: flex-end;
      flex: 1;
      overflow: hidden;
      position: relative;
      gap: 4px;
    }
    .tab {
      display: flex;
      align-items: center;
      padding: 4px 4px;
      background: #e8e8e8;
      border: 1px solid #e0e0e0;
      border-bottom: 1px solid #e0e0e0;
      border-radius: 12px 12px 0 0;
      cursor: pointer;
      user-select: none;
      transition: all 0.2s;
      position: relative;
      flex-shrink: 0;
      width: 280px;
      min-width: 280px;
      max-width: 280px;
      color: #666;
      margin-bottom: -2px;
      opacity: 0.8;
    }
    .tab-status-dot {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      margin-right: 6px;
      flex-shrink: 0;
      transition: background-color 0.3s;
    }
    .tab-status-dot.loading {
      background-color: #ffc107;
    }
    .tab-status-dot.success {
      background-color: #4caf50;
    }
    .tab-status-dot.error {
      background-color: #f44336;
    }
    .tab-status-dot.idle {
      background-color: transparent;
    }
    .tab-icon {
      width: 16px;
      height: 16px;
      margin-right: 6px;
      flex-shrink: 0;
      object-fit: contain;
      border-radius: 2px;
      opacity: 0.7;
    }
    .tab-name {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      min-width: 0;
      color: #666;
      font-size: 14px;
    }
    .tab:hover {
      background: #d8d8d8;
      border-color: #d0d0d0;
      opacity: 0.9;
    }
    .tab.active {
      background: #f0f5ff;
      border: 1px solid #66b3ff;
      border-bottom-color: white;
      z-index: 10;
      opacity: 1;
      box-shadow: 0 -2px 4px rgba(102, 179, 255, 0.1);
    }
    .tab.active .tab-icon {
      opacity: 1;
    }
    .tab.active .tab-name {
      color: #1a73e8;
      font-weight: 500;
    }
    .tab.active::after {
      content: '';
      position: absolute;
      bottom: -2px;
      left: 0;
      right: 0;
      height: 2px;
      background: white;
    }
    .tab-button {
      border-radius: 3px;
      font-size: 14px;
      opacity: 0.6;
      transition: all 0.2s;
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      user-select: none;
      color: #666;
    }
    .tab-button:hover {
      opacity: 1;
      background: rgba(0,0,0,0.08);
      color: #333;
    }
    .tab-mute {
      /* 静音图标使用文本，可以使用 Unicode 符号 */
      cursor: pointer;
    }
    .tab-mute.muted {
      opacity: 1;
      color: #f56565;
    }
    .tab-close {
      padding: 2px 6px;
      border-radius: 3px;
      font-size: 18px;
      opacity: 0.6;
      transition: all 0.2s;
      cursor: pointer;
    }
    .tab-close:hover {
      opacity: 1;
      background: rgba(0,0,0,0.1);
    }
    .content {
      flex: 1;
      position: relative;
      overflow: hidden;
      z-index: 1;
    }
    .webview-container {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      display: none;
    }
    .webview-container.active {
      display: block;
    }
    webview {
      width: 100%;
      height: 100%;
      display: inline-flex;
    }
    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      color: #999;
    }
    .empty-state.hidden {
      display: none;
    }
    .empty-icon {
      margin-bottom: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .empty-icon-img {
      width: 120px;
      height: 120px;
      object-fit: contain;
    }
    .empty-text {
      font-size: 18px;
    }
    .tab-more {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 10px 16px;
      background: #e8e8e8;
      border-left: 1px solid #e0e0e0;
      cursor: pointer;
      user-select: none;
      font-weight: 500;
      color: #667eea;
      flex-shrink: 0;
      min-width: 50px;
      margin-bottom: -2px;
    }
    .tab-more:hover {
      background: #d8d8d8;
    }
    .overflow-dropdown {
      position: fixed;
      background: white;
      border: 1px solid #e0e0e0;
      border-radius: 4px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      z-index: 99999;
      min-width: 300px;
      max-width: 400px;
      max-height: 600px;
      display: none;
      flex-direction: column;
      margin-top: 2px;
    }
    .overflow-dropdown.show {
      display: flex;
    }
    .overflow-search {
      padding: 12px;
      border-bottom: 1px solid #e0e0e0;
    }
    .overflow-search input {
      width: 100%;
      padding: 8px 12px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 14px;
      outline: none;
    }
    .overflow-search input:focus {
      border-color: #667eea;
    }
    .overflow-list {
      overflow-y: auto;
      max-height: 500px;
    }
    .overflow-tab {
      display: flex;
      align-items: center;
      padding: 10px 12px;
      border-bottom: 1px solid #f0f0f0;
      cursor: pointer;
      transition: background 0.2s;
    }
    .overflow-tab:hover {
      background: #f5f5f5;
    }
    .overflow-tab.active {
      background: #e8f0fe;
      color: #667eea;
    }
    .overflow-tab-icon {
      width: 16px;
      height: 16px;
      margin-right: 6px;
      flex-shrink: 0;
      object-fit: contain;
    }
    .overflow-tab-name {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      min-width: 0;
    }
    .overflow-tab-actions {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-left: 8px;
    }
    .overflow-tab-actions .tab-button {
      margin-left: 0;
    }
    .tab-detach {
      color: #667eea;
    }
    .tab-detach:hover {
      color: #5568d3;
    }
    .overflow-tab.hidden {
      display: none;
    }
    /* 更新提示样式 */
    .update-notification {
      position: fixed;
      top: 10px;
      right: 10px;
      background: white;
      border: 1px solid #e0e0e0;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      padding: 16px;
      min-width: 300px;
      max-width: 400px;
      z-index: 10000;
      display: none;
    }
    .update-notification.show {
      display: block;
    }
    .update-notification.info {
      border-left: 4px solid #2196F3;
    }
    .update-notification.success {
      border-left: 4px solid #4CAF50;
    }
    .update-notification.error {
      border-left: 4px solid #f44336;
    }
    .update-notification-title {
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 8px;
      color: #333;
    }
    .update-notification-message {
      font-size: 14px;
      color: #666;
      margin-bottom: 12px;
    }
    .update-notification-progress {
      width: 100%;
      height: 6px;
      background: #f0f0f0;
      border-radius: 3px;
      overflow: hidden;
      margin-bottom: 12px;
    }
    .update-notification-progress-bar {
      height: 100%;
      background: #2196F3;
      transition: width 0.3s;
    }
    .update-notification-actions {
      display: flex;
      gap: 8px;
      justify-content: flex-end;
    }
    .update-notification-btn {
      padding: 6px 16px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      transition: all 0.2s;
    }
    .update-notification-btn-primary {
      background: #2196F3;
      color: white;
    }
    .update-notification-btn-primary:hover {
      background: #1976D2;
    }
    .update-notification-btn-secondary {
      background: #f5f5f5;
      color: #666;
    }
    .update-notification-btn-secondary:hover {
      background: #e0e0e0;
    }
    .update-notification-close {
      position: absolute;
      top: 8px;
      right: 8px;
      cursor: pointer;
      color: #999;
      font-size: 18px;
      width: 24px;
      height: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 4px;
    }
    .update-notification-close:hover {
      background: #f0f0f0;
      color: #333;
    }
  </style>
</head>
<body>
  <!-- 更新提示 -->
  <div class="update-notification" id="updateNotification">
    <div class="update-notification-close" id="updateNotificationClose">×</div>
    <div class="update-notification-title" id="updateNotificationTitle">检查更新</div>
    <div class="update-notification-message" id="updateNotificationMessage"></div>
    <div class="update-notification-progress" id="updateNotificationProgress" style="display: none;">
      <div class="update-notification-progress-bar" id="updateNotificationProgressBar" style="width: 0%;"></div>
    </div>
    <div class="update-notification-actions" id="updateNotificationActions"></div>
  </div>
  <div class="tabs-container">
    <div class="tabs-wrapper" id="tabsWrapper"></div>
    <div class="tab-more" id="tabMore" style="display: none;">
      <span id="tabMoreText">+0</span>
    </div>
    <div class="overflow-dropdown" id="overflowDropdown">
      <div class="overflow-search">
        <input type="text" id="overflowSearch" placeholder="搜索标签...">
      </div>
      <div class="overflow-list" id="overflowList"></div>
    </div>
  </div>

  <div class="content">
    <div class="empty-state" id="emptyState">
      <div class="empty-icon">
        <img src="../icons/avatar.svg" alt="店铺图标" class="empty-icon-img">
      </div>
      <div class="empty-text">等待打开第一个店铺</div>
    </div>
  </div>

  <script>
    let ipcRenderer = null
    try {
      ipcRenderer = require('electron').ipcRenderer
    } catch (e) {
      // contextIsolation 已启用时需要通过 preload.js 访问
    }

    const tabsWrapper = document.getElementById('tabsWrapper')
    const emptyState = document.getElementById('emptyState')
    const tabMore = document.getElementById('tabMore')
    const tabMoreText = document.getElementById('tabMoreText')
    const overflowDropdown = document.getElementById('overflowDropdown')
    const overflowSearch = document.getElementById('overflowSearch')
    const overflowList = document.getElementById('overflowList')
    const contentEl = document.querySelector('.content')

    if (!tabsWrapper || !emptyState || !tabMore || !overflowDropdown) {
      throw new Error('必要的 DOM 元素不存在')
    }

    if (!window.__webviewReadySet || typeof window.__webviewReadySet.add !== 'function') {
      window.__webviewReadySet = new Set()
    }
    if (typeof window.__tabSystemReady !== 'boolean') {
      window.__tabSystemReady = false
    }

    const dispatchTabSystemReady = () => {
      if (!window.__tabSystemReady) {
        window.__tabSystemReady = true
        window.dispatchEvent(new CustomEvent('tab-system-ready', {
          detail: {
            timestamp: Date.now()
          }
        }))
      }
    }

    const markWebviewReadyState = (shopId) => {
      if (!window.__webviewReadySet || typeof window.__webviewReadySet.add !== 'function') {
        window.__webviewReadySet = new Set()
      }
      window.__webviewReadySet.add(shopId)
      window.dispatchEvent(new CustomEvent('webview-ready', {
        detail: { shopId }
      }))
    }

    let overflowTabs = []
    let searchKeyword = ''

    let tabs = []
    let activeTabId = null
    let isSwitchingTab = false // 防止 switchTab 并发调用

    // 点击数字按钮显示/隐藏浮窗
    // 显示浮窗时，数字变成 X，点击 X 关闭浮窗
    tabMore.onclick = (e) => {
      e.stopPropagation()
      if (overflowDropdown.classList.contains('show')) {
        // 浮窗已显示，点击 X 关闭浮窗
        overflowDropdown.classList.remove('show')
        // 恢复显示数字
        updateTabMoreText()
      } else {
        // 计算浮窗位置（相对于数字按钮）
        const tabMoreRect = tabMore.getBoundingClientRect()
        overflowDropdown.style.top = `${tabMoreRect.bottom + 2}px`
        overflowDropdown.style.right = `${window.innerWidth - tabMoreRect.right}px`

        overflowDropdown.classList.add('show')
        // 显示浮窗时，将数字变成 X
        tabMoreText.textContent = '×'
        if (overflowSearch) {
          overflowSearch.focus()
        }
      }
    }
    
    // 更新数字按钮文本的函数
    function updateTabMoreText() {
      if (overflowDropdown.classList.contains('show')) {
        tabMoreText.textContent = '×'
      } else {
        tabMoreText.textContent = `${tabs.length}`
      }
    }

    // 搜索框输入事件
    if (overflowSearch) {
      overflowSearch.oninput = (e) => {
        searchKeyword = e.target.value
        updateOverflowList()
      }
    }

    // 监听窗口大小变化，重新计算布局
    window.addEventListener('resize', () => {
      updateTabLayout()
    })

    // 监听标签容器大小变化
    const resizeObserver = new ResizeObserver(() => {
      updateTabLayout()
    })
    if (tabsWrapper.parentElement) {
      resizeObserver.observe(tabsWrapper.parentElement)
    }

    // 拖拽相关变量
    let draggedTab = null // 当前被拖动的标签
    let dragStartY = 0 // 拖拽开始时的 Y 坐标

    // 使用事件委托，统一处理标签拖拽
    tabsWrapper.addEventListener('dragstart', (e) => {
      const tabEl = e.target.closest('.tab')
      if (!tabEl || !tabEl.dataset.shopId) {
        return
      }

      // 如果点击的是关闭按钮、静音按钮，不处理拖拽
      if (e.target.classList.contains('tab-close') || e.target.classList.contains('tab-mute')) {
        e.preventDefault()
        return
      }

      // 检查：如果当前窗口只有一个标签，不允许拖动
      if (tabs.length <= 1) {
        e.preventDefault()
        return
      }

      const shopId = tabEl.dataset.shopId
      draggedTab = tabs.find(t => t.shopId === shopId)
      dragStartY = e.clientY

      // 设置拖拽效果
      e.dataTransfer.effectAllowed = 'move'
      // 设置一个自定义数据，避免浏览器默认行为
      e.dataTransfer.setData('text/plain', shopId)
    })

    tabsWrapper.addEventListener('dragover', (e) => {
      // 允许拖拽
      e.preventDefault()
      e.dataTransfer.dropEffect = 'move'
    })

    // 监听整个窗口的 dragend 事件，检测是否拖动出标签栏
    document.addEventListener('dragend', (e) => {
      if (!draggedTab) return

      const tabEl = e.target.closest('.tab')
      if (!tabEl || !tabEl.dataset.shopId) return

      const shopId = draggedTab.shopId
      const tabsContainerRect = tabsWrapper.getBoundingClientRect()
      const mouseY = e.clientY

      // 检查鼠标是否在标签栏区域外（向下拖动）
      // 如果鼠标在标签栏下方，且距离超过一定阈值，则分离窗口
      const threshold = 50 // 拖动超过 50px 才触发分离
      if (mouseY > tabsContainerRect.bottom + threshold) {
        // 触发分离窗口
        detachTabToNewWindow(shopId)
      }

      // 重置拖拽状态
      draggedTab = null
      dragStartY = 0
    })

    // 使用事件委托，统一处理标签点击
    tabsWrapper.addEventListener('click', (e) => {
      // 如果点击的是关闭按钮或静音按钮，不处理（它们有自己的处理逻辑）
      if (e.target.classList.contains('tab-close') || e.target.classList.contains('tab-mute')) {
        return
      }

      // 找到被点击的标签元素
      let tabEl = e.target.closest('.tab')
      if (!tabEl || !tabEl.dataset.shopId) {
        return
      }

      const shopId = tabEl.dataset.shopId

      if (activeTabId !== shopId && !isSwitchingTab) {
        e.stopPropagation()
        switchTabInternal(shopId)
      }
    })

    ipcRenderer.on('create-tab', (event, data) => {
      const { shopId, shopName, partition, shopIcon } = data
      if (typeof window.createTab === 'function') {
        window.createTab(shopId, shopName, partition, shopIcon)
      }
    })

    async function createTabInternal(shopId, shopName, partition, shopIcon) {
      if (!tabsWrapper) {
        const error = new Error('tabsWrapper 元素不存在，无法创建标签页')
        throw error
      }

      const existingTab = tabs.find(t => t.shopId === shopId)
      if (existingTab) {
        switchTabInternal(shopId)
        return
      }

      const tab = {
        shopId,
        shopName,
        shopIcon,
        partition,
        element: null,
        container: null,
        webview: null
      }

      const tabEl = document.createElement('div')
      tabEl.className = 'tab'
      tabEl.dataset.shopId = shopId
      tabEl.draggable = true // 启用拖拽

      // 创建加载状态点
      const statusDot = document.createElement('div')
      statusDot.className = 'tab-status-dot idle'
      tab.statusDot = statusDot
      tab.loadStatus = 'idle' // idle, loading, success, error
      tabEl.appendChild(statusDot)

      // 创建图标（如果存在）
      if (shopIcon) {
        const tabIcon = document.createElement('img')
        tabIcon.className = 'tab-icon'
        tabIcon.src = shopIcon
        tabIcon.alt = shopName || '店铺图标'
        tabIcon.style.width = '16px'
        tabIcon.style.height = '16px'
        tabIcon.style.marginRight = '6px'
        tabIcon.style.flexShrink = '0'
        tabIcon.style.objectFit = 'contain'
        tabEl.appendChild(tabIcon)
      }

      const tabName = document.createElement('span')
      tabName.className = 'tab-name'
      tabName.textContent = shopName || `店铺-${shopId}`

      // 创建静音按钮
      const tabMute = document.createElement('span')
      tabMute.className = 'tab-button tab-mute'
      tabMute.textContent = '🔊' // 未静音图标
      tabMute.dataset.muted = 'false'
      tabMute.onclick = (e) => {
        e.stopPropagation()
        toggleMute(shopId)
      }

      // 创建关闭按钮
      const tabClose = document.createElement('span')
      tabClose.className = 'tab-button tab-close'
      tabClose.textContent = '×'
      tabClose.onclick = (e) => {
        e.stopPropagation()
        closeTab(shopId)
      }

      tabEl.appendChild(tabName)
      tabEl.appendChild(tabMute)
      tabEl.appendChild(tabClose)

      // 在 tab 对象中保存静音按钮引用和状态
      tab.muteButton = tabMute
      tab.isMuted = false

      // 不需要在这里绑定点击事件，因为已经在 tabsWrapper 上使用事件委托了

      tab.element = tabEl

      const container = document.createElement('div')
      container.className = 'webview-container'
      container.dataset.shopId = shopId
      container.id = `webview-container-${shopId}`

      let webview = null
      try {
        webview = document.createElement('webview')
        if (!webview || !webview.setAttribute) {
          throw new Error('createElement 方式失败')
        }
      } catch (e) {
        container.innerHTML = `<webview id="webview-${shopId}" partition="${partition}" src="about:blank" allowpopups="true" nodeintegration="false" webpreferences="nativeWindowOpen=yes" style="width: 100%; height: 100%;"></webview>`
        webview = container.querySelector('webview')
        if (!webview) {
          throw new Error('无法创建 webview 元素')
        }
      }

      webview.id = `webview-${shopId}`
      webview.setAttribute('partition', partition)
      if (!webview.src) {
        webview.src = 'about:blank'
      }
      webview.setAttribute('allowpopups', 'true')
      webview.setAttribute('nodeintegration', 'false')
      webview.setAttribute('webpreferences', 'nativeWindowOpen=yes')
      webview.style.width = '100%'
      webview.style.height = '100%'

      if (!container.contains(webview)) {
        container.appendChild(webview)
      }

      // 等待 webview DOM 就绪，避免加载 URL 时出现 ERR_ABORTED 错误
      // 将 ready 状态保存到 tab 对象中
      tab.webviewReady = false
      
      // 使用多种方式确保 webview 就绪
      const markWebviewReady = () => {
        if (!tab.webviewReady) {
          tab.webviewReady = true
          markWebviewReadyState(shopId)
        }
      }
      
      // 方法1: 监听 dom-ready 事件
      const onDomReady = () => {
        markWebviewReady()
        webview.removeEventListener('dom-ready', onDomReady)
      }
      webview.addEventListener('dom-ready', onDomReady)
      
      // 方法2: 使用 getWebContents（如果可用）
      if (webview.getWebContents) {
        webview.getWebContents().then(() => {
          markWebviewReady()
        }).catch(() => {
          // getWebContents 失败，依赖 dom-ready 事件
        })
      }
      
      // 方法3: 超时保护（3秒后标记为就绪，避免无限等待）
      setTimeout(() => {
        markWebviewReady()
      }, 3000)

      const contentEl = document.querySelector('.content')
      if (!contentEl) {
        throw new Error('.content 元素不存在，无法添加 webview 容器')
      }

      contentEl.appendChild(container)

      const webviewInDOM = container.querySelector('webview')
      if (!webviewInDOM) {
        throw new Error(`webview 元素未添加到容器，无法继续`)
      }

      tab.container = container
      tab.webview = webview

      // 监听 webview 加载事件，更新状态点
      if (webview.addEventListener) {
        let loadTimeout = null
        let lastStatus = 'idle'
        let finishLoadCount = 0
        let startLoadCount = 0

        // 开始加载
        webview.addEventListener('did-start-loading', () => {
          startLoadCount++
          finishLoadCount = 0 // 重置完成计数
          // 清除之前的超时
          if (loadTimeout) {
            clearTimeout(loadTimeout)
            loadTimeout = null
          }
          lastStatus = 'loading'
          updateTabStatus(shopId, 'loading')
        })

        // 加载完成
        webview.addEventListener('did-finish-load', () => {
          finishLoadCount++
          const currentFinishCount = finishLoadCount
          
          // 清除之前的超时
          if (loadTimeout) {
            clearTimeout(loadTimeout)
            loadTimeout = null
          }
          
          // 延迟检查，确保加载真正完成
          loadTimeout = setTimeout(() => {
            // 检查是否在延迟期间又有新的加载开始
            if (finishLoadCount !== currentFinishCount) {
              // 如果计数变了，说明又有新的加载，不更新状态
              return
            }
            
            // 再次检查 webview 是否还在加载
            let stillLoading = false
            try {
              if (webview.getWebContents) {
                webview.getWebContents().then(webContents => {
                  if (webContents) {
                    stillLoading = webContents.isLoading()
                  }
                  // 再次检查计数，确保没有新的加载
                  if (!stillLoading && finishLoadCount === currentFinishCount) {
                    lastStatus = 'success'
                    updateTabStatus(shopId, 'success')
                  }
                }).catch(() => {
                  // 如果无法获取 webContents，直接设为成功
                  if (finishLoadCount === currentFinishCount) {
                    lastStatus = 'success'
                    updateTabStatus(shopId, 'success')
                  }
                })
              } else if (webview.isLoading && typeof webview.isLoading === 'function') {
                stillLoading = webview.isLoading()
                if (!stillLoading && finishLoadCount === currentFinishCount) {
                  lastStatus = 'success'
                  updateTabStatus(shopId, 'success')
                }
              } else {
                // 如果无法检查，直接设为成功
                if (finishLoadCount === currentFinishCount) {
                  lastStatus = 'success'
                  updateTabStatus(shopId, 'success')
                }
              }
            } catch (e) {
              // 出错时设为成功
              if (finishLoadCount === currentFinishCount) {
                lastStatus = 'success'
                updateTabStatus(shopId, 'success')
              }
            }
          }, 800)
        })

        // 加载失败
        webview.addEventListener('did-fail-load', (event) => {
          // 清除之前的超时
          if (loadTimeout) {
            clearTimeout(loadTimeout)
            loadTimeout = null
          }
          // 检查是否是真正的加载失败（不是用户导航）
          // errorCode: -3 是 ERR_ABORTED（用户取消或导航），不算失败
          if (event.errorCode !== -3) {
            lastStatus = 'error'
            updateTabStatus(shopId, 'error')
          } else {
            // 如果是用户导航取消，检查是否还在加载
            setTimeout(() => {
              if (webview.isLoading && !webview.isLoading()) {
                lastStatus = 'success'
                updateTabStatus(shopId, 'success')
              }
            }, 100)
          }
        })

        // 定期检查加载状态（防止事件丢失或状态不同步）
        const statusCheckInterval = setInterval(() => {
          const tab = tabs.find(t => t.shopId === shopId)
          if (!tab || !tab.webview) {
            clearInterval(statusCheckInterval)
            return
          }

          try {
            // 使用 getWebContents 检查加载状态
            if (tab.webview.getWebContents) {
              tab.webview.getWebContents().then(webContents => {
                if (webContents) {
                  const isLoading = webContents.isLoading()
                  if (isLoading && lastStatus !== 'loading') {
                    lastStatus = 'loading'
                    updateTabStatus(shopId, 'loading')
                  } else if (!isLoading && lastStatus === 'loading') {
                    // 如果不在加载但状态还是 loading，更新为成功
                    // 但需要确保没有新的加载开始
                    setTimeout(() => {
                      if (lastStatus === 'loading') {
                        lastStatus = 'success'
                        updateTabStatus(shopId, 'success')
                      }
                    }, 500)
                  }
                }
              }).catch(() => {
                // 如果无法获取 webContents，忽略
              })
            } else if (tab.webview.isLoading && typeof tab.webview.isLoading === 'function') {
              const isLoading = tab.webview.isLoading()
              if (isLoading && lastStatus !== 'loading') {
                lastStatus = 'loading'
                updateTabStatus(shopId, 'loading')
              } else if (!isLoading && lastStatus === 'loading') {
                // 延迟更新，确保没有新的加载
                setTimeout(() => {
                  if (lastStatus === 'loading') {
                    lastStatus = 'success'
                    updateTabStatus(shopId, 'success')
                  }
                }, 500)
              }
            }
          } catch (e) {
            // 忽略检查错误
          }
        }, 1000)

        // 保存清理函数
        tab.statusCheckInterval = statusCheckInterval
      }

      tabs.push(tab)

      if (!tabsWrapper) {
        const error = new Error('tabsWrapper 不存在，无法添加标签元素')
        throw error
      }
      
      tabsWrapper.appendChild(tabEl)

      switchTabInternal(shopId)
      window.tabs = tabs

      // 延迟更新标签布局，确保 DOM 已渲染
      setTimeout(() => {
        updateTabLayout()
      }, 50)
    }

    // 更新标签布局，检测溢出并显示数字按钮
    function updateTabLayout() {
      if (tabs.length === 0) {
        tabMore.style.display = 'none'
        overflowDropdown.classList.remove('show')
        return
      }

      // 先显示所有标签以计算宽度
      tabs.forEach(tab => {
        if (tab.element) {
          tab.element.style.display = 'flex'
        }
      })

      // 强制重排以获取实际宽度
      void tabsWrapper.offsetHeight

      const containerWidth = tabsWrapper.parentElement.offsetWidth
      const tabMoreWidth = 60 // 数字按钮的估算宽度

      let visibleCount = 0
      let totalWidth = 0

      // 计算可见标签数量（需要考虑数字按钮的宽度）
      for (let i = 0; i < tabs.length; i++) {
        const tab = tabs[i]
        if (!tab.element) continue

        const tabRect = tab.element.getBoundingClientRect()
        const tabWidth = tabRect.width || 280

        // 检查当前标签 + 数字按钮是否能放下
        const spaceNeeded = totalWidth + tabWidth + tabMoreWidth

        if (spaceNeeded > containerWidth) {
          // 放不下当前标签和数字按钮，从当前标签开始隐藏
          tab.element.style.display = 'none'
          break
        } else {
          // 可以显示当前标签
          totalWidth += tabWidth
          visibleCount++
          tab.element.style.display = 'flex'
        }
      }

      // 数字按钮一直显示
      tabMore.style.display = 'flex'
      
      // 更新数字按钮文本（如果浮窗显示则显示 X，否则显示数字）
      updateTabMoreText()

      // 计算超出主标签栏的标签页
      const overflowCount = tabs.length - visibleCount
      if (overflowCount > 0) {
        overflowTabs = tabs.slice(visibleCount)
      } else {
        overflowTabs = []
        // 如果没有溢出标签，关闭浮窗
        overflowDropdown.classList.remove('show')
        // 更新数字按钮文本
        updateTabMoreText()
      }

      // 更新浮窗中的标签列表
      updateOverflowList()
    }

    // 更新浮窗中的标签列表
    // 修改：显示当前主窗口的所有标签，而不是只显示溢出的标签
    function updateOverflowList() {
      if (!overflowList) return

      overflowList.innerHTML = ''

      // 显示所有标签，而不是只显示 overflowTabs
      const allTabs = tabs

      const filteredTabs = searchKeyword
        ? allTabs.filter(tab =>
            (tab.shopName || `店铺-${tab.shopId}`).toLowerCase().includes(searchKeyword.toLowerCase())
          )
        : allTabs

      // 如果过滤后的列表为空，且浮窗正在显示，关闭浮窗
      if (filteredTabs.length === 0 && overflowDropdown.classList.contains('show')) {
        // 只有在所有标签也为空时才关闭（搜索时列表为空是正常的）
        if (allTabs.length === 0) {
          overflowDropdown.classList.remove('show')
          // 更新数字按钮文本
          updateTabMoreText()
        }
      }

      filteredTabs.forEach(tab => {
        const overflowTabEl = document.createElement('div')
        overflowTabEl.className = 'overflow-tab'
        overflowTabEl.dataset.shopId = tab.shopId

        if (tab.shopId === activeTabId) {
          overflowTabEl.classList.add('active')
        }

        // 创建图标（如果存在）
        if (tab.shopIcon) {
          const tabIcon = document.createElement('img')
          tabIcon.className = 'overflow-tab-icon'
          tabIcon.src = tab.shopIcon
          tabIcon.alt = tab.shopName || '店铺图标'
          tabIcon.style.width = '16px'
          tabIcon.style.height = '16px'
          tabIcon.style.marginRight = '6px'
          tabIcon.style.flexShrink = '0'
          tabIcon.style.objectFit = 'contain'
          overflowTabEl.appendChild(tabIcon)
        }

        const tabName = document.createElement('span')
        tabName.className = 'overflow-tab-name'
        tabName.textContent = tab.shopName || `店铺-${tab.shopId}`

        const actions = document.createElement('div')
        actions.className = 'overflow-tab-actions'

        // 静音按钮
        const muteBtn = document.createElement('span')
        muteBtn.className = 'tab-button tab-mute'
        muteBtn.textContent = tab.isMuted ? '🔇' : '🔊'
        if (tab.isMuted) {
          muteBtn.classList.add('muted')
        }
        muteBtn.onclick = (e) => {
          e.stopPropagation()
          toggleMute(tab.shopId)
          updateOverflowList()
        }

        // 脱离按钮（点击脱离到新窗口）
        // 只有当标签数量大于1时才显示脱离按钮
        if (tabs.length > 1) {
          const detachBtn = document.createElement('span')
          detachBtn.className = 'tab-button tab-detach'
          detachBtn.textContent = '↗' // 使用箭头图标表示脱离
          detachBtn.title = '脱离到新窗口'
          detachBtn.onclick = (e) => {
            e.stopPropagation()
            detachTabToNewWindow(tab.shopId)
          }
          actions.appendChild(detachBtn)
        }

        // 关闭按钮
        const closeBtn = document.createElement('span')
        closeBtn.className = 'tab-button tab-close'
        closeBtn.textContent = '×'
        closeBtn.onclick = (e) => {
          e.stopPropagation()
          closeTab(tab.shopId)
        }

        actions.appendChild(muteBtn)
        actions.appendChild(closeBtn)

        overflowTabEl.appendChild(tabName)
        overflowTabEl.appendChild(actions)

        // 浮窗中的标签不可拖动
        overflowTabEl.draggable = false

        // 点击标签切换到该标签
        overflowTabEl.onclick = (e) => {
          if (!e.target.classList.contains('tab-button')) {
            switchTabInternal(tab.shopId)
            overflowDropdown.classList.remove('show')
          }
        }

        overflowList.appendChild(overflowTabEl)
      })
    }

    function switchTabInternal(shopId) {
      // 防止重复切换和并发调用
      if (activeTabId === shopId || isSwitchingTab) {
        return
      }

      if (tabs.length === 0) {
        return
      }

      isSwitchingTab = true

      try {
        activeTabId = shopId

        tabs.forEach((tab, index) => {
          if (!tab.element || !tab.container) {
            return
          }
          const isActive = tab.shopId === shopId

          if (isActive) {
            tab.element.classList.add('active')
            tab.container.classList.add('active')
          } else {
            tab.element.classList.remove('active')
            tab.container.classList.remove('active')
          }
        })

        if (tabs.length > 0) {
          emptyState.classList.add('hidden')
        }

        // 更新浮窗中的激活状态
        updateOverflowList()
      } catch (error) {
      } finally {
        isSwitchingTab = false
      }
    }

    function toggleMute(shopId) {
      const tab = tabs.find(t => t.shopId === shopId)
      if (!tab || !tab.webview) {
        return
      }

      try {
        const currentMuted = tab.isMuted || false
        const newMuted = !currentMuted

        // 设置 webview 的静音状态
        // Electron webview 标签可以使用 getWebContents() 方法
        if (tab.webview.getWebContents) {
          tab.webview.getWebContents().then(webContents => {
            if (webContents) {
              webContents.setAudioMuted(newMuted)
              // 更新状态
              updateMuteState(tab, newMuted)
            }
          }).catch(error => {
            // 备用方法：直接设置属性
            if (tab.webview.setAttribute) {
              tab.webview.setAttribute('audiomuted', String(newMuted))
              updateMuteState(tab, newMuted)
            }
          })
        } else if (tab.webview.setAttribute) {
          // 备用方法：通过属性设置
          tab.webview.setAttribute('audiomuted', String(newMuted))
          updateMuteState(tab, newMuted)
        }
      } catch (error) {
      }
    }

    // 更新标签页加载状态
    function updateTabStatus(shopId, status) {
      const tab = tabs.find(t => t.shopId === shopId)
      if (!tab || !tab.statusDot) {
        return
      }

      // 移除所有状态类
      tab.statusDot.classList.remove('loading', 'success', 'error', 'idle')
      
      // 添加新状态类
      if (status === 'loading' || status === 'success' || status === 'error') {
        tab.statusDot.classList.add(status)
        tab.loadStatus = status
      } else {
        tab.statusDot.classList.add('idle')
        tab.loadStatus = 'idle'
      }
    }

    // 更新静音状态（同时更新主标签栏和浮窗中的按钮）
    function updateMuteState(tab, isMuted) {
      tab.isMuted = isMuted

      // 更新主标签栏中的静音按钮
      if (tab.muteButton) {
        tab.muteButton.dataset.muted = String(isMuted)
        if (isMuted) {
          tab.muteButton.textContent = '🔇'
          tab.muteButton.classList.add('muted')
        } else {
          tab.muteButton.textContent = '🔊'
          tab.muteButton.classList.remove('muted')
        }
      }

      // 更新浮窗中的静音按钮
      updateOverflowList()
    }

    function closeTab(shopId) {
      const tabIndex = tabs.findIndex(t => t.shopId === shopId)
      if (tabIndex === -1) return

      const tab = tabs[tabIndex]

      // 清理状态检查定时器
      if (tab.statusCheckInterval) {
        clearInterval(tab.statusCheckInterval)
      }

      tab.element.remove()
      tab.container.remove()

      tabs.splice(tabIndex, 1)

      if (window.__webviewReadySet && typeof window.__webviewReadySet.delete === 'function') {
        window.__webviewReadySet.delete(shopId)
      }

      if (activeTabId === shopId) {
        if (tabs.length > 0) {
          const newIndex = Math.min(tabIndex, tabs.length - 1)
          switchTabInternal(tabs[newIndex].shopId)
        } else {
          activeTabId = null
          emptyState.classList.remove('hidden')
        }
      }

      ipcRenderer.invoke('close-shop-window', shopId)

      // 更新标签布局
      updateTabLayout()
    }

    let isCreatingTab = false
    const creatingTabIds = new Set()
    const failedTabIds = new Set()

    window.createTab = async function(shopId, shopName, partition, shopIcon) {
      const existingTab = tabs.find(t => t.shopId === shopId)
      if (existingTab) {
        switchTabInternal(shopId)
        failedTabIds.delete(shopId)
        return true
      }

      if (creatingTabIds.has(shopId)) {
        return false
      }

      if (failedTabIds.has(shopId)) {
        return false
      }

      isCreatingTab = true
      creatingTabIds.add(shopId)

      try {
        await createTabInternal(shopId, shopName, partition, shopIcon)

        await new Promise(resolve => setTimeout(resolve, 100))

        const verifyTab = tabs.find(t => t.shopId === shopId)

        if (!verifyTab) {
          const error = new Error(`标签页创建后验证失败: ${shopId} - 找不到标签页对象`)
          throw error
        }

        if (!verifyTab.webview) {
          const error = new Error(`标签页创建后验证失败: ${shopId} - 标签页对象存在但没有 webview`)
          throw error
        }

        failedTabIds.delete(shopId)
        return true
      } catch (e) {
        failedTabIds.add(shopId)
        creatingTabIds.delete(shopId)
        isCreatingTab = false
        return false
      } finally {
        if (creatingTabIds.has(shopId)) {
          creatingTabIds.delete(shopId)
          isCreatingTab = false
        }
      }
    }

    window.loadShopUrl = async function(shopId, url) {
      try {
        const tab = tabs.find(t => t.shopId === shopId)
        
        if (!tab || !tab.webview) {
          setTimeout(() => {
            const retryTab = tabs.find(t => t.shopId === shopId)
            if (retryTab && retryTab.webview) {
              window.loadShopUrl(shopId, url)
            }
          }, 500)
          return false
        }
        
        const webview = tab.webview
        
        // 等待 webview DOM 就绪
        const waitForReady = () => {
          return new Promise((resolve) => {
            // 方法1: 使用 dom-ready 事件
            const onDomReady = () => {
              webview.removeEventListener('dom-ready', onDomReady)
              resolve()
            }
            
            // 方法2: 使用 getWebContents（如果可用）
            if (webview.getWebContents) {
              webview.getWebContents().then(() => {
                webview.removeEventListener('dom-ready', onDomReady)
                resolve()
              }).catch(() => {
                // getWebContents 失败，使用 dom-ready
                webview.addEventListener('dom-ready', onDomReady)
              })
            } else {
              // 没有 getWebContents，使用 dom-ready
              webview.addEventListener('dom-ready', onDomReady)
            }
            
            // 超时保护（最多等待 5 秒）
            setTimeout(() => {
              webview.removeEventListener('dom-ready', onDomReady)
              resolve()
            }, 5000)
          })
        }
        
        // 等待 webview 就绪
        await waitForReady()
        
        // 设置 URL
        webview.setAttribute('src', url)
        
        return true
      } catch (e) {
        // 加载失败
        updateTabStatus(shopId, 'error')
        return false
      }
    }

    window.switchTab = function(shopId) {
      // 防止重复切换和并发调用
      if (activeTabId === shopId || isSwitchingTab) {
        return
      }

      // 直接调用内部函数 switchTabInternal，避免作用域冲突
      switchTabInternal(shopId)
    }

    window.setShopCookies = function(shopId, cookies) {
      const tab = tabs.find(t => t.shopId === shopId)
      if (tab && tab.webview) {
        // Cookie 通过 partition 自动隔离
      }
    }

    // ==================== 自动更新 UI ====================
    const updateNotification = document.getElementById('updateNotification')
    const updateNotificationTitle = document.getElementById('updateNotificationTitle')
    const updateNotificationMessage = document.getElementById('updateNotificationMessage')
    const updateNotificationProgress = document.getElementById('updateNotificationProgress')
    const updateNotificationProgressBar = document.getElementById('updateNotificationProgressBar')
    const updateNotificationActions = document.getElementById('updateNotificationActions')
    const updateNotificationClose = document.getElementById('updateNotificationClose')

    // 显示更新通知
    function showUpdateNotification(type, title, message, actions = []) {
      updateNotification.className = `update-notification ${type} show`
      updateNotificationTitle.textContent = title
      updateNotificationMessage.textContent = message
      updateNotificationActions.innerHTML = ''
      
      actions.forEach(action => {
        const btn = document.createElement('button')
        btn.className = `update-notification-btn ${action.class || 'update-notification-btn-primary'}`
        btn.textContent = action.text
        btn.onclick = action.onclick
        updateNotificationActions.appendChild(btn)
      })
    }

    // 隐藏更新通知
    function hideUpdateNotification() {
      updateNotification.classList.remove('show')
    }

    // 关闭按钮
    if (updateNotificationClose) {
      updateNotificationClose.onclick = () => {
        hideUpdateNotification()
      }
    }

    // 监听更新事件
    let downloadCompleteTimeout = null // 下载完成超时检查
    let autoInstallTimer = null // 自动安装倒计时定时器
    let autoInstallCountdown = 5 // 自动安装倒计时秒数
    
    // 更新自动安装消息
    function updateAutoInstallMessage(version, countdown) {
      if (updateNotificationMessage) {
        updateNotificationMessage.textContent = `版本 ${version} 已下载完成。${countdown}秒后自动重启安装更新。`
      }
    }
    
    if (ipcRenderer) {
      // 检查更新中
      ipcRenderer.on('checking-for-update', () => {
        showUpdateNotification('info', '检查更新', '正在检查是否有新版本...', [])
      })

      // 发现新版本
      ipcRenderer.on('update-available', (event, info) => {
        const version = info.version || '新版本'
        showUpdateNotification('info', '发现新版本', `发现新版本 ${version}，是否下载？`, [
          {
            text: '下载',
            class: 'update-notification-btn-primary',
            onclick: async () => {
              try {
                const result = await ipcRenderer.invoke('download-update')
                if (result.success) {
                  showUpdateNotification('info', '下载中', '正在下载更新，请稍候...', [])
                  updateNotificationProgress.style.display = 'block'

                  updateNotificationProgressBar.style.width = '0%' // 重置进度条
                }
              } catch (error) {
                showUpdateNotification('error', '下载失败', error.message || '下载更新失败', [
                  {
                    text: '关闭',
                    class: 'update-notification-btn-secondary',
                    onclick: () => hideUpdateNotification()
                  }
                ])
              }
            }
          },
          {
            text: '稍后',
            class: 'update-notification-btn-secondary',
            onclick: () => hideUpdateNotification()
          }
        ])
      })

      // 没有新版本 - 关闭检查更新弹窗，静默处理
      ipcRenderer.on('update-not-available', (event, info) => {
        // 关闭之前显示的"检查更新"弹窗
        hideUpdateNotification()
      })

      // 下载进度
      ipcRenderer.on('download-progress', (event, progress) => {
        const percent = Math.round(progress.percent || 0)
        const transferred = formatBytes(progress.transferred || 0)
        const total = formatBytes(progress.total || 0)
        
        updateNotificationProgressBar.style.width = `${percent}%`
        
        // 如果下载进度达到 100%，立即更新 UI 状态
        if (percent >= 100) {
          // 立即更新 UI，显示下载完成状态
          updateNotificationTitle.textContent = '下载完成'
          updateNotificationMessage.textContent = '下载完成，正在准备安装...'
          updateNotificationProgressBar.style.width = '100%'
          
          // 清除之前的超时
          if (downloadCompleteTimeout) {
            clearTimeout(downloadCompleteTimeout)
          }
          
          // 2秒后如果还没收到 update-downloaded 事件，手动显示安装提示（备用机制）
          downloadCompleteTimeout = setTimeout(() => {
            // 检查是否已经显示了安装提示（通过检查标题是否为"更新已下载完成"）
            if (updateNotificationTitle.textContent !== '更新已下载完成' && updateNotificationTitle.textContent !== '下载完成') {
              // 如果已经显示了其他提示，不重复显示
              return
            }
            
            // 如果标题还是"下载完成"，说明 update-downloaded 事件还没来，手动显示安装提示
            if (updateNotificationTitle.textContent === '下载完成') {
              // 确保进度条显示为100%
              updateNotificationProgressBar.style.width = '100%'
              
              // 延迟隐藏进度条，让用户看到100%完成
              setTimeout(() => {
                // 隐藏进度条
                updateNotificationProgress.style.display = 'none'
                
                // 开始自动安装倒计时
                autoInstallCountdown = 5
                updateAutoInstallMessage('新版本', autoInstallCountdown)
                
                // 显示安装提示，带倒计时
                showUpdateNotification('success', '更新已下载完成', `更新已下载完成。${autoInstallCountdown}秒后自动重启安装更新。`, [
                  {
                    text: '立即重启',
                    class: 'update-notification-btn-primary',
                    onclick: () => {
                      // 清除自动安装定时器
                      if (autoInstallTimer) {
                        clearInterval(autoInstallTimer)
                        autoInstallTimer = null
                      }
                      ipcRenderer.invoke('install-update')
                    }
                  },
                  {
                    text: '稍后',
                    class: 'update-notification-btn-secondary',
                    onclick: () => {
                      // 清除自动安装定时器
                      if (autoInstallTimer) {
                        clearInterval(autoInstallTimer)
                        autoInstallTimer = null
                      }
                      hideUpdateNotification()
                    }
                  }
                ])
                
                // 开始倒计时
                autoInstallTimer = setInterval(() => {
                  autoInstallCountdown--
                  if (autoInstallCountdown > 0) {
                    updateAutoInstallMessage('新版本', autoInstallCountdown)
                  } else {
                    // 倒计时结束，自动重启
                    clearInterval(autoInstallTimer)
                    autoInstallTimer = null
                    ipcRenderer.invoke('install-update').catch(() => {
                      // 静默处理错误
                    })
                  }
                }, 1000)
              }, 500)
            }
          }, 2000)
        } else {
          // 确保标题和消息正确显示下载状态
          updateNotificationTitle.textContent = '下载中'
          updateNotificationMessage.textContent = `下载进度: ${percent}% (${transferred} / ${total})`
        }
      })

      // 下载完成
      ipcRenderer.on('update-downloaded', (event, info) => {
        // 清除超时检查
        if (downloadCompleteTimeout) {
          clearTimeout(downloadCompleteTimeout)
          downloadCompleteTimeout = null
        }
        
        // 清除之前的自动安装定时器
        if (autoInstallTimer) {
          clearInterval(autoInstallTimer)
          autoInstallTimer = null
        }
        
        const version = info.version || '新版本'
        
        // 确保进度条显示为100%
        updateNotificationProgressBar.style.width = '100%'
        
        // 显示进度条，然后延迟隐藏（让用户看到100%完成）
        updateNotificationProgress.style.display = 'block'
        
        // 延迟显示安装提示，让用户看到100%的进度条
        setTimeout(() => {
          // 隐藏进度条
          updateNotificationProgress.style.display = 'none'
          
          // 开始自动安装倒计时
          autoInstallCountdown = 5
          updateAutoInstallMessage(version, autoInstallCountdown)
          
          // 显示安装提示，带倒计时
          showUpdateNotification('success', '更新已下载完成', `版本 ${version} 已下载完成。${autoInstallCountdown}秒后自动重启安装更新。`, [
            {
              text: '立即重启',
              class: 'update-notification-btn-primary',
              onclick: () => {
                // 清除自动安装定时器
                if (autoInstallTimer) {
                  clearInterval(autoInstallTimer)
                  autoInstallTimer = null
                }
                ipcRenderer.invoke('install-update').catch(() => {
                  // 静默处理错误
                })
              }
            },
            {
              text: '稍后',
              class: 'update-notification-btn-secondary',
              onclick: () => {
                // 清除自动安装定时器
                if (autoInstallTimer) {
                  clearInterval(autoInstallTimer)
                  autoInstallTimer = null
                }
                hideUpdateNotification()
              }
            }
          ])
          
          // 开始倒计时
          autoInstallTimer = setInterval(() => {
            autoInstallCountdown--
            if (autoInstallCountdown > 0) {
              updateAutoInstallMessage(version, autoInstallCountdown)
            } else {
              // 倒计时结束，自动重启
              clearInterval(autoInstallTimer)
              autoInstallTimer = null
              ipcRenderer.invoke('install-update').catch(() => {
                // 静默处理错误
              })
            }
          }, 1000)
        }, 500)
      })
    }

    // 格式化字节数
    function formatBytes(bytes) {
      if (!bytes || bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
    }

    // 手动检查更新（可以通过菜单或按钮调用）
    window.checkForUpdate = async function() {
      if (!ipcRenderer) {
        return
      }
      
      try {
        showUpdateNotification('info', '检查更新', '正在检查更新...', [])
        const result = await ipcRenderer.invoke('check-for-update')
        if (!result.success) {
          showUpdateNotification('error', '检查失败', result.message || '检查更新失败', [
            {
              text: '关闭',
              class: 'update-notification-btn-secondary',
              onclick: () => hideUpdateNotification()
            }
          ])
        }
        // 如果成功，等待事件通知
      } catch (error) {
        showUpdateNotification('error', '检查失败', error.message || '检查更新失败', [
          {
            text: '关闭',
            class: 'update-notification-btn-secondary',
            onclick: () => hideUpdateNotification()
          }
        ])
      }
    }


    /**
     * 将标签页分离到新窗口
     * @param {string} shopId - 店铺ID
     */
    async function detachTabToNewWindow(shopId) {
      const tab = tabs.find(t => t.shopId === shopId)
      if (!tab) {
        return
      }

      try {
        // 获取标签页的当前 URL
        let currentUrl = 'about:blank'
        if (tab.webview) {
          try {
            currentUrl = tab.webview.src || tab.webview.getURL() || 'about:blank'
            // 如果 URL 是 about:blank 或空，尝试从 shopTabs 获取
            if (!currentUrl || currentUrl === 'about:blank') {
              // 通过 IPC 获取标签页信息（如果主进程有保存）
              // 这里我们先使用当前 URL，主进程会从 shopTabs 中获取正确的 URL
            }
          } catch (e) {
          }
        }

        // 通过 IPC 通知主进程创建新窗口并迁移标签页
        const result = await ipcRenderer.invoke('detach-tab-to-window', {
          shopId: shopId,
          shopName: tab.shopName,
          partition: tab.partition,
          url: currentUrl
        })

        if (result.success) {
          // 从当前窗口移除标签页
          closeTab(shopId)
        } else {
        }
      } catch (error) {
      }
    }

    dispatchTabSystemReady()
  </script>
</body>
</html>
